package com.android.webrtcsdkdev

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.android.webrtcsdkdev.net.ApiJavaClient
import com.android.webrtcsdkdev.net.ICallback
import com.android.webrtcsdkdev.net.bean.ResponseCreateGroupControl
import com.google.gson.Gson
import com.vc.videosdk.xlog.XLogUtil


class GroupControlStreamActivity : Activity() {
    val TAG = "MainActivity"
    private var edt_uri: EditText? = null

    //主控实例id
    private var edt_master_device_id: EditText? = null

    //从控实例id
    private var edt_slave_instance_ids: EditText? = null
    private var bt_start: Button? = null
    private var bt_cancel: Button? = null
    private var info: TextView? = null
    private var encoder: Spinner? = null
    private var sizeSpinner: Spinner? = null
    private var cardSizeSpinner: Spinner? = null
    private var densitySpinner: Spinner? = null
    private var fpsSpinner: Spinner? = null
    private var bitrate: EditText? = null
    private var authEdit: EditText? = null
    private var videoCodec = "VP8"
    private var direct = 0
    private var width = 0
    private var height = 0;
    private var videofps = 30
    private val REQUEST_EXTERNAL_STORAGE = 1
    private var density = 480
    private var cardWidth = 1080
    private var cardHeight = 1920;
    private var gpsDelay = 300


    private val permissions = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.INTERNET,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    fun verifyStoragePermissions(activity: Activity?) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {//Build.VERSION_CODES.R
                if (!Environment.isExternalStorageManager()) {
                    val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    startActivity(intent);
                    return;
                }
            } else {
                //检测是否有写的权限
                val permission = ActivityCompat.checkSelfPermission(
                    activity!!,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(
                        this,
                        permissions,
                        REQUEST_EXTERNAL_STORAGE
                    )

                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy")
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_group_control_stream)
        verifyStoragePermissions(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val intent = Intent()
            val packageName = packageName
            val pm = getSystemService(POWER_SERVICE) as PowerManager
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                intent.setData(Uri.parse("package:$packageName"))
                startActivity(intent)
                Toast.makeText(
                    this,
                    "ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
        SharedPHelper.getInstance(this).open("vclusters", 1)


        val displayMetrics = resources.displayMetrics
        var screenWidth = displayMetrics!!.widthPixels
        var screenHeight = displayMetrics.heightPixels
        Log.d(TAG, "screenWidth:$screenWidth screenHeight:$screenHeight")
        edt_uri = findViewById(R.id.edt_uri)
        edt_master_device_id = findViewById(R.id.edt_master_device_id)
        edt_slave_instance_ids = findViewById(R.id.edt_slave_instance_ids)
        bt_start = findViewById(R.id.bt_start)
        bt_cancel = findViewById(R.id.bt_cancel)
        info = findViewById(R.id.info);
        encoder = findViewById(R.id.encoder_spinner)
        sizeSpinner = findViewById(R.id.spinner_size)
        fpsSpinner = findViewById(R.id.encoder_fps)
        bitrate = findViewById(R.id.bitrate)
        authEdit = findViewById(R.id.auths)
        cardSizeSpinner = findViewById(R.id.card_size)
        densitySpinner = findViewById(R.id.card_density)

        encoder!!.setSelection(1)
        fpsSpinner!!.setSelection(2)
        sizeSpinner!!.setSelection(3)
        cardSizeSpinner!!.setSelection(0)
        densitySpinner!!.setSelection(0)

        val serverUrl = SharedPHelper.getInstance(this).getString(VideoConstant.STREAM_SERVER_URL)
        val deviceMasterInstanceId =
            SharedPHelper.getInstance(this).getString(VideoConstant.STREAM_MASTER_DEVICE_ID)
        val deviceSlaveInstanceId =
            SharedPHelper.getInstance(this).getString(VideoConstant.STREAM_SLAVE_DEVICE_ID)
        if (serverUrl.isNotEmpty()) {
            edt_uri?.setText(serverUrl)
        }

        if (deviceMasterInstanceId.isNotEmpty()) {
            edt_master_device_id?.setText(deviceMasterInstanceId)
        }

        if (deviceSlaveInstanceId.isNotEmpty()) {
            edt_slave_instance_ids?.setText(deviceSlaveInstanceId)
        }


        setUpSessionButton()
    }

    private var sessionId: String = "1293310035242196992"
    private fun setUpSessionButton() {
        bt_start!!.setOnClickListener {
            val serverUrl = edt_uri?.text.toString()
            val masterInstanceId = edt_master_device_id?.text.toString()
            val slaveInstanceId = edt_slave_instance_ids?.text.toString()

            if (serverUrl.isNotEmpty() && masterInstanceId.isNotEmpty() && slaveInstanceId.isNotEmpty()) {
                SharedPHelper.getInstance(this)
                    .putString(VideoConstant.STREAM_SERVER_URL, serverUrl)

                SharedPHelper.getInstance(this)
                    .putString(VideoConstant.STREAM_MASTER_DEVICE_ID, masterInstanceId)
                SharedPHelper.getInstance(this)
                    .putString(VideoConstant.STREAM_SLAVE_DEVICE_ID, slaveInstanceId)

                val slaveInstanceIdList = slaveInstanceId.split(",")
                val slaveInstanceIdArrayList: ArrayList<String> =
                    ArrayList(slaveInstanceIdList.toMutableList())
                ApiJavaClient.createGroupControl(
                    masterInstanceId,
                    slaveInstanceIdArrayList,
                    object : ICallback<Any> {
                        override fun onSuccess(obj: Any) {
                            Toast.makeText(
                                this@GroupControlStreamActivity,
                                "创建群控会话成功",
                                Toast.LENGTH_SHORT
                            ).show()
                            var createGroupControl = Gson().fromJson(
                                obj.toString(),
                                ResponseCreateGroupControl::class.java
                            )

                            XLogUtil.d("createGroupControl onSuccess:$obj,,,,,,session_id:${createGroupControl.session_id}")

                            SharedPHelper.getInstance(this@GroupControlStreamActivity)
                                .putString(VideoConstant.STREAM_SESSION_ID, createGroupControl.session_id)

                            val intent = Intent()
                            intent.setClass(
                                this@GroupControlStreamActivity,
                                StreamActivity::class.java
                            )
                            intent.putExtra("uri", serverUrl)
                            intent.putExtra("room", masterInstanceId)//传主控instanceId
                            intent.putExtra("videocodec", videoCodec)
                            intent.putExtra("bitrate", bitrate!!.text.toString())
                            intent.putExtra("videofps", videofps.toString())
                            intent.putExtra("auths", authEdit!!.text.toString())
                            intent.putExtra("sessionId", createGroupControl.session_id)

                            var localVideoCallEnabled = true
                            var localAudioCallEnabled = true
                            var localVideoReceiveEnabled = true
                            var localAudioReceiveEnabled = true
                            var remoteVideoCallEnabled = true
                            var remoteAudioCallEnabled = true
                            var remoteVideoReceiveEnabled = true
                            var remoteAudioReceiveEnabled = true

                            intent.putExtra("localVideoCallEnabled", localVideoCallEnabled)
                            intent.putExtra("localAudioCallEnabled", localAudioCallEnabled)
                            intent.putExtra("localVideoReceiveEnabled", localVideoReceiveEnabled)
                            intent.putExtra("localAudioReceiveEnabled", localAudioReceiveEnabled)
                            intent.putExtra("remoteVideoCallEnabled", remoteVideoCallEnabled)
                            intent.putExtra("remoteAudioCallEnabled", remoteAudioCallEnabled)
                            intent.putExtra("remoteVideoReceiveEnabled", remoteVideoReceiveEnabled)
                            intent.putExtra("remoteAudioReceiveEnabled", remoteAudioReceiveEnabled)
                            intent.putExtra("width", width)
                            intent.putExtra("height", height)
                            intent.putExtra("cardWidth", cardWidth)
                            intent.putExtra("cardHeight", cardHeight)
                            intent.putExtra("density", density)
                            intent.putExtra("gpsDelay", gpsDelay)

                            startActivity(intent)

                        }

                        override fun onFailed(code: String, msg: String) {
                            XLogUtil.e("createGroupControl onFailed code:$code,,,msg:$msg")
                            Toast.makeText(
                                this@GroupControlStreamActivity,
                                "创建群控会话失败",
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                    })


            } else {
                Toast.makeText(
                    this@GroupControlStreamActivity,
                    "信令服务器/主控实例Id/从控实例ID不能为空",
                    Toast.LENGTH_SHORT
                ).show()
            }

        }



        bt_cancel!!.setOnClickListener {
            val sessionID= SharedPHelper.getInstance(this@GroupControlStreamActivity).getString(VideoConstant.STREAM_SESSION_ID)
            ApiJavaClient.cancelGroupControl(sessionID, object : ICallback<Any> {
                override fun onSuccess(obj: Any) {
                    XLogUtil.d("cancelGroupControl onSuccess:$obj")
                }

                override fun onFailed(code: String, msg: String) {
                    XLogUtil.e("cancelGroupControl onFailed code:$code,,,,msg:$msg")
                }
            })
        }



        encoder?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    videoCodec = "H264 Baseline"
                } else if (position == 1) {
                    videoCodec = "H264 High"
                } else if (position == 2) {
                    videoCodec = "H265"
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }
        fpsSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    videofps = 15;
                } else if (position == 1) {
                    videofps = 20;
                } else if (position == 2) {
                    videofps = 30;
                } else if (position == 3) {
                    videofps = 35;
                } else if (position == 4) {
                    videofps = 40;
                } else if (position == 5) {
                    videofps = 45;
                } else if (position == 6) {
                    videofps = 50;
                } else if (position == 7) {
                    videofps = 55;
                } else if (position == 8) {
                    videofps = 60;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }


        sizeSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    width = 640;
                    height = 360;
                } else if (position == 1) {
                    width = 800;
                    height = 450;
                } else if (position == 2) {
                    width = 960;
                    height = 540;
                } else if (position == 3) {
                    width = 1280;
                    height = 720;
                } else if (position == 4) {
                    width = 1920;
                    height = 1080;
                } else if (position == 5) {
                    width = 2280;
                    height = 1020;
                } else if (position == 6) {
                    width = 2560;
                    height = 1440;
                } else if (position == 7) {
                    width = 2560;
                    height = 1600;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }

        cardSizeSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    cardWidth = 720;
                    cardHeight = 1280;
                } else if (position == 1) {
                    cardWidth = 1080;
                    cardHeight = 1920;
                } else if (position == 2) {
                    cardWidth = 1080;
                    cardHeight = 2400;
                } else if (position == 3) {
                    cardWidth = 1440;
                    cardHeight = 2560;
                } else if (position == 4) {
                    cardWidth = 1600;
                    cardHeight = 2560;
                } else if (position == 5) {
                    cardWidth = 1280;
                    cardHeight = 720;
                } else if (position == 6) {
                    cardWidth = 1920;
                    cardHeight = 1080;
                } else if (position == 7) {
                    cardWidth = 2400;
                    cardHeight = 1080;
                } else if (position == 8) {
                    cardWidth = 2560;
                    cardHeight = 1440;
                } else if (position == 9) {
                    cardWidth = 2560;
                    cardHeight = 1600;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }
        densitySpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    density = 320;
                } else if (position == 1) {
                    density = 480;
                } else if (position == 2) {
                    density = 560;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }
    }
}
